from sqlalchemy.orm import Session
from db_manage.conversation_manage import delete_conversation, delete_message_by_conversation, get_messages, delete_message
from db_manage.conversation_manage import create_message
from utils.call_llm import call_llm, call_llm_stream  # 假设这是调用 LLM 的函数

async def chat(db: Session, conversation_id: int, user_id: int, user_message: str):
    # 保存用户消息
    user_message_record = create_message(db=db, conversation_id=conversation_id, content=user_message, user_id=user_id)

    # 调用 LLM 获取回复
    llm_response = ""
    response = call_llm_stream('',user_message)
    for chunk in response:
        if len(chunk.choices)>0 and hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
            chunk_content = chunk.choices[0].delta.content
            # Print the incoming text without a newline (simulate real-time streaming)
            llm_response += chunk_content
            yield chunk_content
    # print(llm_response)
    # 保存 LLM 返回的消息 thinking 和 assistant 角色的消息
    # llm_message_record = create_message(db=db, conversation_id=conversation_id, content=llm_response, user_id=user_id, role="thinking")
    llm_message_record = create_message(db=db, conversation_id=conversation_id, content=llm_response, user_id=user_id, role="assistant")
    # print(llm_message_record)


def delete_conversation_and_messages(db: Session, conversation_id: int, user_id: int):
    # 首先删除与对话相关的所有消息
    messages = delete_message_by_conversation(db, conversation_id,user_id=user_id)
    if messages.get("error","") != "":
        return messages
    
    # 然后删除对话
    return delete_conversation(db, conversation_id, user_id=user_id)
